$(document).ready(() => {

    const serverHost = window.config.serverHost

    const user = JSON.parse(window.localStorage.getItem("user"))
    if (!user) {
        alert('USER UN LOGIN!')
        return;
    }
    console.log(user)
    $('#current_username').text(user.customerName)

    // Get Address List
    $('#address_list').on('click', () => {
        $('#op_content').html('')

        let addressSet = (JSON.parse(window.localStorage.getItem("user"))).addressSet
        console.log(addressSet)

        let content = ''

        addressSet.forEach(item => {
            content += `<div>
                            <p>Name: <strong>${item.addressContactPerson}</strong> </p>
                            <p>Tel&nbsp;: <strong>${item.addressContactTel}</strong>
                                <a onclick="removeData('${item.addressId}')" class="btn btn-default pull-right" style="margin-right: 10px; line-height: 15px;">Delete</a>
                                <a onclick="updateData('${item.addressId}', '${item.addressContactPerson}', '${item.addressContactTel}', '${item.addressName}')" class="btn btn-default pull-right" role="button" class="btn" data-toggle="modal" style="margin-right: 10px; line-height: 15px;">Update</a>
                            </p>
                            <p>Address: <strong>${item.addressName}</strong></p>
                        </div>
                        <hr style="margin-top: 10px; margin-bottom: 10px;" />`;
        });
        $('#op_title').html(`Address Manager <a href="#createModal" role="button" data-toggle="modal" class="btn btn-warning" style="color: #eee; font-size: 14px;">New</a>`)

        $('#op_content').html(content)

    })

    $('#order_list').on('click', () => {
        console.log('Order list')
        $('#op_content').html('')

        const customerId = user.customerId;
        console.log(customerId)

        let content = ''
        const serverHost = window.config.serverHost
        $.ajax({
            url: `${serverHost}/order/orderlist?customerId=${customerId}`,
            type: 'GET',
            success: data => {
                console.log(data)
                let content = ''
                data.forEach(item => {
                    console.log('xxx', item)
                    let foodNames = ''
                    let foodCounts = 0
                    let foodPrice = 0.00
                    item.orderFoods.forEach(e => {
                        foodNames += e.foodName + ' / '
                        foodCounts += e.count
                        foodPrice += parseFloat((e.foodPrice) * e.count)
                    })
                    let statusCode = item.orderStatus
                    let orderStatus = ''
                    switch (statusCode) {
                        case 0:
                            orderStatus = '等待商家接单'
                            break;
                        case 1:
                            orderStatus = '商家已拒单'
                            break;
                        case 2:
                            orderStatus = '商家已接单'
                            break;
                        case 3:
                            orderStatus = '配送中'
                            break;
                        case 4:
                            orderStatus = '订单已完成'
                            break;
                        case 5:
                            orderStatus = '订单已取消'
                            break;
                    }

                    let createTime = new Date();
                    createTime.setTime(item.createTime * 1000);
                    let time = (createTime.toLocaleString()).split(' ')[1]

                    if (statusCode == 0) {
                        content = content + `<div class="orderblock">
                                    <div class="orderblock-item orderblock-rstinfo clearfix"><a class="logo" href="./orderdetail.html?orderId=${item.orderId}"><img src="${item.merchant_headpic}" alt="pic"></a>
                                        <h3 class="name"><a class="inherit" href="./orderdetail.html?orderId=${item.orderId}">${item.merchantName}</a></h3>
                                        <p class="product">${foodNames}</p><a class="productnum" href="./orderdetail.html?orderId=orderId=${item.orderId}">共<i class="count">${foodCounts.toFixed(2)}</i>个菜品&gt;</a></div>
                                    <div class="orderblock-item orderblock-tim">${time}</div>
                                    <div class="orderblock-item orderblock-price">
                                        <p class="total">¥${foodPrice.toFixed(2)}</p></div>
                                    <div class="orderblock-item orderblock-status">
                                        <p class="status end">${orderStatus}</p><a class="statuslink" href="./orderdetail.html?orderId=${item.orderId}">订单详情</a></div>
                                    <div class="orderblock-item orderblock-status" style="padding-top: 10px;">
                                    <a class="statuslink" style="padding: 3px;" onclick="cancelOrder('${item.orderId}')" href="#">取消订单</a>
                            </div>
                        </div>`
                    } else if (statusCode == 3) {
                        content = content + `<div class="orderblock">
                                    <div class="orderblock-item orderblock-rstinfo clearfix"><a class="logo" href="./orderdetail.html?orderId=${item.orderId}"><img src="${item.merchant_headpic}" alt="pic"></a>
                                        <h3 class="name"><a class="inherit" href="./orderdetail.html?orderId=${item.orderId}">${item.merchantName}</a></h3>
                                        <p class="product">${foodNames}</p><a class="productnum" href="./orderdetail.html?orderId=orderId=${item.orderId}">共<i class="count">${foodCounts.toFixed(2)}</i>个菜品&gt;</a></div>
                                    <div class="orderblock-item orderblock-tim">${time}</div>
                                    <div class="orderblock-item orderblock-price">
                                        <p class="total">¥${foodPrice.toFixed(2)}</p></div>
                                    <div class="orderblock-item orderblock-status">
                                        <p class="status end">${orderStatus}</p><a class="statuslink" href="./orderdetail.html?orderId=${item.orderId}">订单详情</a></div>
                                    <div class="orderblock-item orderblock-status" style="padding-top: 10px;">
                                    <a class="statuslink" style="padding: 3px;" onclick="confirmOrder('${item.orderId}')" href="#">确认收货</a>
                                    </div>
                                </div>`
                    } else {
                        content = content + `<div class="orderblock">
                                    <div class="orderblock-item orderblock-rstinfo clearfix"><a class="logo" href="./orderdetail.html?orderId=${item.orderId}"><img src="${item.merchant_headpic}" alt="pic"></a>
                                        <h3 class="name"><a class="inherit" href="./orderdetail.html?orderId=${item.orderId}">${item.merchantName}</a></h3>
                                        <p class="product">${foodNames}</p><a class="productnum" href="./orderdetail.html?orderId=orderId=${item.orderId}">共<i class="count">${foodCounts.toFixed(2)}</i>个菜品&gt;</a></div>
                                    <div class="orderblock-item orderblock-tim">${time}</div>
                                    <div class="orderblock-item orderblock-price">
                                        <p class="total">¥${foodPrice.toFixed(2)}</p></div>
                                    <div class="orderblock-item orderblock-status">
                                        <p class="status end">${orderStatus}</p><a class="statuslink" href="./orderdetail.html?orderId=${item.orderId}">订单详情</a></div>
                                </div>`
                    }
                })
                $('#op_title').text('Orders')
                $('#op_content').html(content)
            },
            error: () => {
                console.log('Request Error!')
            }
        })
    })

    // update address
    $('#update_submit').on('click', () => {

        $('#errorText').text('')
        let addressId = $('#u_addressId').val()
        let addressContactPerson = $('#u_concactPerson').val();
        let addressContactTel = $('#u_concactTel').val();
        let addressName = $('#u_addressName').val();
        let customerId = JSON.parse(window.localStorage.getItem('user')).customerId

        console.log(addressId, addressContactPerson, addressContactTel, addressName, customerId)

        $.ajax({
            url: `${serverHost}/user/updateaddress`,
            type: 'POST',
            data: {
                addressId: addressId,
                addressContactPerson: addressContactPerson,
                addressContactTel: addressContactTel,
                addressName: addressName,
                customerId: customerId
            },
            success: data => {
                console.log(data)
                let status = data.status
                if (status == 'SUCCESS') {
                    let user = JSON.parse(window.localStorage.getItem('user'))
                    user.addressSet = data.data
                    window.localStorage.setItem('user', JSON.stringify(user))
                    $('#address_list').click();

                    $('#updateModal').modal('hide');
                } else {
                    $('#errorText').text('Update Address Fail. Please Try Again Later..')
                }
            },
            error: () => {
                console.log('Update Address Fail...')
                $('#errorText').text('Server Error! Please Try Again Later..')
            }
        })
    })

    // insert a new Address
    $('#create_submit').on('click', () => {
        $('a_errorText').text('')

        $('#createModal').modal('show');
        let addressContactPerson = $('#a_concactPerson').val()
        let addressContactTel = $('#a_concactTel').val()
        let addressName = $('#a_addressName').val()
        let customerId = JSON.parse(window.localStorage.getItem('user')).customerId
        console.log(addressContactPerson, addressContactTel, addressName, customerId)
        $.ajax({
            url: `${serverHost}/user/addaddress`,
            type: 'POST',
            data: {
                addressContactPerson: addressContactPerson,
                addressContactTel: addressContactTel,
                addressName: addressName,
                customerId: customerId
            },
            success: data => {
                console.log(data)
                let status = data.status
                if (status == 'SUCCESS') {
                    $('#createModal').modal('hide');
                    let user = JSON.parse(window.localStorage.getItem('user'))
                    user.addressSet = data.data
                    window.localStorage.setItem('user', JSON.stringify(user))
                    $('#address_list').click();

                    $('#a_concactPerson').val('')
                    $('#a_concactTel').val('')
                    $('#a_addressName').val('')
                } else {
                    $('a_errorText').text('Add Address Fail. Please Try Again Later...')
                }
            },
            error: () => {
                console.log('Server Error! Please Try Again Later...')
                $('a_errorText').text('Server Error! Please Try Again Later...')
            }
        })
    })

    // remove a address
    $('#remove_submit').on('click', () => {

        $('#removeText').text('Are you sure you want to delete this address?')

        let addressId = $('#removeAddresId').val()
        let customerId = JSON.parse(window.localStorage.getItem('user')).customerId
        $.ajax({
            url: `${serverHost}/user/deleteaddress`,
            type: 'POST',
            data: {
                addressId: addressId,
                customerId: customerId
            },
            success: data => {
                console.log(data)
                let status = data.status
                if (status == 'SUCCESS') {
                    let user = JSON.parse(window.localStorage.getItem('user'))
                    user.addressSet = data.data
                    window.localStorage.setItem('user', JSON.stringify(user))
                    $('#removeModal').modal('hide');
                    $('#address_list').click();
                } else {
                    $('#removeText').text('Remove Address Fail. Please Try Again Latter...');
                }
            },
            error: () => {
                console.log('Server Error! Please Try Again Later...')
                $('#removeText').text('Server Error! Please Try Again Latter...')
            }
        })
    })
})

function updateData(addressId, concactPerson, concactTel, addressName) {
    console.log(addressId, concactPerson, concactTel, addressName)
    $('#u_addressId').val('')
    $('#u_concactPerson').val('')
    $('#u_concactTel').val('')
    $('#u_addressName').val('')

    $('#updateModal').modal('show');

    $('#u_addressId').val(addressId)
    $('#u_concactPerson').val(concactPerson)
    $('#u_concactTel').val(concactTel)
    $('#u_addressName').val(addressName)
}

function removeData(addressId) {
    console.log(addressId)
    $('#removeModal').modal('show');
    $('#removeAddresId').val(addressId)
}

function confirmOrder(orderId) {
    const serverHost = window.config.serverHost
    $.ajax({
        url: `${serverHost}/order/confirmorder?orderId=${orderId}`,
        type: 'GET',
        success: data => {
            console.log(data)
            let status = data.status
            if (status == 'SUCCESS') {
                $('#order_list').click();
            } else {
                alert('Confrim Order Fail.')
            }
        },
        error: () => {
            console.log('Server Error! Please Try Again Later...')
            alert('Confrim Order Fail.')
        }
    })
}

function cancelOrder(orderId) {
    const serverHost = window.config.serverHost
    $.ajax({
        url: `${serverHost}/order/cancelorder?orderId=${orderId}`,
        type: 'GET',
        success: data => {
            console.log(data)
            let status = data.status
            if (status == 'SUCCESS') {
                $('#order_list').click();
            } else {
                alert('Cancel Order Fail.')
            }
        },
        error: () => {
            console.log('Server Error! Please Try Again Later...')
            alert('Cancel Order Fail.')
        }
    })
}